# -*- coding:utf-8 -*-
"""
登录视图
"""
from django.contrib import auth, messages
from django.shortcuts import render, redirect
from .forms import LoginForm


def login_in(request):
    """
    定义用户登录事件
    """
    # 检查是请求方式是GET还是POST,GET直接返回首页，POST则执行登录验证.
    if request.user.is_authenticated:
        return redirect('main:main_index')

    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            login_data = form.cleaned_data
            user = auth.authenticate(
                username=login_data["username"],
                password=login_data["password"]
                )

            if user and user.is_active:
                auth.login(request, user)
                return redirect('main:main_index')
            elif user:
                messages.add_message(request, messages.ERROR, '帐号已停用')
                return redirect('auth:login')
            else:
                messages.add_message(request, messages.ERROR, '帐号或密码不正确!')
                return redirect('auth:login')
    else:
        form = LoginForm()
        return render(request, 'style/login/index.html', {'login_form': form})


# 定义登出view.
def login_out(request):
    """
    用户登出事件视图
    """
    auth.logout(request)
    return redirect('auth:login')
